package lc20240602;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 求岛屿数量。
 * @date 2024/6/2 20:43
 */
public class GetIslandsNum {
    public static void main(String[] args) {
        char[][] grid={
                {'1','1','1','1','0'},
                {'1','1','0','1','0'},
                {'1','1','0','0','0'},
                {'0','0','0','0','0'}
        };
        GetIslandsNum getIslandsNum=new GetIslandsNum();
        System.out.println(getIslandsNum.numIslands(grid));
    }

    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        int resNum = 0;
        //行数
        int nr = grid.length;
        //列数
        int nc = grid[0].length;
        for (int i = 0; i < nr; i++) {
            for (int i1 = 0; i1 < nc; i1++) {
                if (grid[i][i1] == '1') {
                    resNum++;
                    dfs(grid, i, i1);
                }
            }
        }
        return resNum;
    }

    //深度优先搜索。
    private void dfs(char[][] grid, int r, int c) {
        int nr = grid.length;
        //列数
        int nc = grid[0].length;
        if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
            return;
        }
        grid[r][c] = '0';
        dfs(grid, r + 1, c);
        dfs(grid, r - 1, c);
        dfs(grid, r, c + 1);
        dfs(grid, r, c - 1);
    }
}
